package com.soecode.lyf.web;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.soecode.lyf.config.JWTUtils;
import com.soecode.lyf.dto.Result;
import com.soecode.lyf.entity.AdminInfo;
import com.soecode.lyf.entity.Comment;
import com.soecode.lyf.entity.Sign;
import com.soecode.lyf.entity.UserInfo;
import com.soecode.lyf.service.AdminService;

@Controller
@RequestMapping("/admin") // url:/模块/资源/{id}/细分 /seckill/list
public class AdminController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	final int ERROR = 1;
    final int SUCCESS = 0;

    @Autowired
    private AdminService adminservice;
    
    @ResponseBody
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public Result editUser(String username,String password,Model model) throws Exception {
    	Result result = new Result();
    	if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(password)) {
    		AdminInfo admin = new AdminInfo();
    		admin.setUsername(username);
    		admin.setPassword(password);
    		AdminInfo admininfo = adminservice.login(admin);
    		if(admininfo!=null) {
    		System.out.println("查询到的用户id"+admininfo.getId()+"用户名"+admininfo.getUsername());
    		if(!StringUtils.isEmpty(admininfo.getId())) { // 不是第一次登录，只更新token
                JWTUtils jwt = new JWTUtils();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String Token = jwt.createToken(admininfo.getId());// 生成token
                Calendar nowTime = Calendar.getInstance();
                nowTime.add(Calendar.HOUR, 24 * 7);
                Date experiesDate = nowTime.getTime(); // 设置token有效期(7天)
                //DecodedJWT login = jwt.verifyToken(token); // 解密
                String exp = df.format(experiesDate); // TOKEN有效期7天后的日期
                System.out.println("用户名"+username+"密码"+password);
                int i = adminservice.updateAdminToken(null,Token,exp,username,password);
                if(i!=0) {
            		HashMap<String,String> adminMap = new HashMap<String,String>();
            		adminMap.put("userid", admininfo.getId());
            		adminMap.put("token",Token);
            		adminMap.put("exp", exp);
            		model.addAttribute("AdminInfo",adminMap);
            		result = new Result(0,model,"登录成功");
                }
    		}else {// 第一次登录，生成userid
                JWTUtils jwt = new JWTUtils();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String Token = jwt.createToken(admininfo.getId());// 生成token
                Calendar nowTime = Calendar.getInstance();
                nowTime.add(Calendar.HOUR, 24 * 7);
                Date experiesDate = nowTime.getTime(); // 设置token有效期(7天)
                //DecodedJWT login = jwt.verifyToken(token); // 解密
                String exp = df.format(experiesDate); // TOKEN有效期7天后的日期
            	String uuid = UUID.randomUUID().toString().replace("-", "");	
            	System.out.println("第一次登录用户名"+username+"密码"+password);
            	int i = adminservice.updateAdminToken(uuid,Token,exp,username,password);
            	if(i!=0) {
            		HashMap<String,String> adminMap = new HashMap<String,String>();
            		adminMap.put("userid", uuid);
            		adminMap.put("token",Token);
            		adminMap.put("exp", exp);
            		model.addAttribute("AdminInfo",adminMap);
            		result = new Result(0,model,"登录成功");
            	}
    		}
    		}else {
    			result = new Result(1,"登录失败");
    		}
    	}    	
    	return result;
    }
    
    /**
     * 编辑用户信息
     * @param userName
     * @param passWord
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "editUser", method = RequestMethod.GET)
    public Result editUser(String eduid,String nickname,String signature,int age,String sex,String emial, String phone,String img, String birthday,String experience,String integral) throws Exception {
    	Result result = new Result();
    	UserInfo userinfo = new UserInfo();
    	//if(!StringUtils.isEmpty(eduid)&&!StringUtils.isEmpty(nickname)&&!StringUtils.isEmpty(signature)&&!StringUtils.isEmpty(age)&&!StringUtils.isEmpty(sex)&&!StringUtils.isEmpty(emial)&&!StringUtils.isEmpty(phone)&&!StringUtils.isEmpty(img)&&!StringUtils.isEmpty(birthday)&&!StringUtils.isEmpty(experience)&&!StringUtils.isEmpty(integral)) {
    	userinfo.setId(eduid);
    	userinfo.setNickname(nickname);
    	userinfo.setSignature(signature);
    	userinfo.setAge(age);
    	userinfo.setSex(sex);
    	userinfo.setEmial(emial);
    	userinfo.setPhone(phone);
    	userinfo.setImg(img);
    	userinfo.setBirthday(birthday);
    	userinfo.setExperience(experience);
    	userinfo.setIntegral(integral);
    	int i = adminservice.updateUserInfo(userinfo);
    	if(i!=0) {
    		result = new Result(0,"修改成功");
    	}else {
    		result = new Result(1,"修改失败");
    	}
    	//}else {
    	//	result = new Result(1,"缺少参数");
    	//}
    	return result;
    }


    /**
     * 查询用户信息
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "SelectUser", method = RequestMethod.GET)
    public Result SelectUser(int page,int size,Model model) throws Exception {
    	Result result = new Result();
		PageHelper.startPage(page,size);
		List<UserInfo> userList = adminservice.getUserList();
		PageInfo<UserInfo> page1 = new PageInfo<UserInfo>(userList);
        model.addAttribute("PAGEINFO",userList);
        model.addAttribute("PAGESUM",page1.getTotal());
        result = new Result(0,model,"用户表数据获取成功");
    	return result;
    }

    /**
     * 删除用户信息
     * @param userName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "deleteUser", method = RequestMethod.GET)
    public Result deleteUser(String deleteid) throws Exception {
    	Result result = new Result();
        if (StringUtils.isEmpty(deleteid)) {
        	result = new Result(ERROR, "用户id不能为空");
        }else {
        synchronized (deleteid.intern()){
            //开始删除
            int i = adminservice.deleteUser(deleteid);
            if(i!=0) {
            	result = new Result(SUCCESS, "删除成功");
            }else {
            	result = new Result(ERROR, "删除失败");
            }
        }
        }
        return result;
    }
    /**
     * 查询签到信息
     * @param page
     * @param size
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "SelectSign", method = RequestMethod.GET)
    public Result SelectSign(int page,int size,Model model) throws Exception {
    	Result result = new Result();
		PageHelper.startPage(page,size);
		List<Sign> userList = adminservice.getSignList();
		PageInfo<Sign> page1 = new PageInfo<Sign>(userList);
        model.addAttribute("PAGEINFO",userList);
        model.addAttribute("PAGESUM",page1.getTotal());
        result = new Result(0,model,"签到表数据获取成功");
    	return result;
    }
    /**
     * 删除用户签到信息
     * @param userName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "deleteSign", method = RequestMethod.GET)
    public Result deleteSign(String deleteid) throws Exception {
    	Result result = new Result();
        if (StringUtils.isEmpty(deleteid)) {
        	result = new Result(ERROR, "用户id不能为空");
        }else {
        synchronized (deleteid.intern()){
            //开始删除
            int i = adminservice.deleteSign(deleteid);
            if(i!=0) {
            	result = new Result(SUCCESS, "删除成功");
            }else {
            	result = new Result(ERROR, "删除失败");
            }
        }
        }
        return result;
    }
    /**
     * 查询问题表信息
     * @param page
     * @param size
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "SelectQuestion", method = RequestMethod.GET)
    public Result SelectQuestion(int page,int size,Model model) throws Exception {
    	Result result = new Result();
		PageHelper.startPage(page,size);
		List<Comment> List = adminservice.getQuestionList();
		PageInfo<Comment> page1 = new PageInfo<Comment>(List);
        model.addAttribute("PAGEINFO",List);
        model.addAttribute("PAGESUM",page1.getTotal());
        result = new Result(0,model,"签到表数据获取成功");
    	return result;
    }
    /**
     * 删除问题表信息
     * @param userName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "deleteQuestion", method = RequestMethod.GET)
    public Result deleteQuestion(String deleteid) throws Exception {
    	Result result = new Result();
        if (StringUtils.isEmpty(deleteid)) {
        	result = new Result(ERROR, "用户id不能为空");
        }else {
        synchronized (deleteid.intern()){
            //开始删除
            int i = adminservice.deleteQuestion(deleteid);
            if(i!=0) {
            	result = new Result(SUCCESS, "删除成功");
            }else {
            	result = new Result(ERROR, "删除失败");
            }
        }
        }
        return result;
    }
    /**
     * 查询评论表信息
     * @param page
     * @param size
     * @param model
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "SelectComment", method = RequestMethod.GET)
    public Result SelectComment(int page,int size,Model model) throws Exception {
    	Result result = new Result();
		PageHelper.startPage(page,size);
		List<Comment> List = adminservice.getCommentList();
		PageInfo<Comment> page1 = new PageInfo<Comment>(List);
        model.addAttribute("PAGEINFO",List);
        model.addAttribute("PAGESUM",page1.getTotal());
        result = new Result(0,model,"签到表数据获取成功");
    	return result;
    }
    /**
     * 删除评论表信息
     * @param userName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "deleteComment", method = RequestMethod.GET)
    public Result Comment(String deleteid) throws Exception {
    	Result result = new Result();
        if (StringUtils.isEmpty(deleteid)) {
        	result = new Result(ERROR, "用户id不能为空");
        }else {
        synchronized (deleteid.intern()){
            //开始删除
            int i = adminservice.deleteComment(deleteid);
            if(i!=0) {
            	result = new Result(SUCCESS, "删除成功");
            }else {
            	result = new Result(ERROR, "删除失败");
            }
        }
        }
        return result;
    }
}
